package top.wshape1.shiziapi.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import top.wshape1.shiziapi.common.domain.ProjectSearch;
import top.wshape1.shiziapi.common.utils.R;
import top.wshape1.shiziapi.project.config.RabbitMqConfig;
import top.wshape1.shiziapi.project.domain.Read;
import top.wshape1.shiziapi.project.feign.SearchFeignService;
import top.wshape1.shiziapi.project.mapper.ReadMapper;
import top.wshape1.shiziapi.project.service.ReadService;

import java.util.Date;
import java.util.concurrent.CompletableFuture;

/**
 * @author Wshape1
 * @description 针对表【t_project_read】的数据库操作Service实现
 * @since 2024-01-22 16:56:12
 */
@Service
public class ReadServiceImpl extends ServiceImpl<ReadMapper, Read>
        implements ReadService {

//    @Resource
//    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RabbitTemplate rabbitTemplate;

//    @Resource
//    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private SearchFeignService searchFeignService;

    @Override
    public void read(Long projectId) {
        //好像不需要再存到Redis，直接存ElasticSearch就可以了

        CompletableFuture.runAsync(() -> {
            ProjectSearch projectSearch = new ProjectSearch();
            projectSearch.setId(projectId);
            projectSearch.setOperate(101);
            projectSearch.setUpdateTime(new Date());
            rabbitTemplate.convertAndSend(
                    RabbitMqConfig.SHIZIAPI_PROJECT_ELASTIC_EXCHANGE,
                    RabbitMqConfig.SHIZIAPI_PROJECT_ELASTIC_BINDING,
                    projectSearch
            );
        });

//        String readKey = RedisConstant.PROJECT_READ_KEY + projectId;
//
//        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
//        script.setResultType(Long.class);
//        script.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/readProject.lua")));
//        Long execute = redisTemplate.execute(script, List.of(readKey));
//
//        if (execute != null && execute == 1)
//            CompletableFuture.runAsync(() -> {
//                ProjectSearch projectSearch = new ProjectSearch();
//                projectSearch.setId(projectId);
//                projectSearch.setOperate(101);
//                rabbitTemplate.convertAndSend(
//                        RabbitMqConfig.SHIZIAPI_PROJECT_ELASTIC_EXCHANGE,
//                        RabbitMqConfig.SHIZIAPI_PROJECT_ELASTIC_BINDING,
//                        projectSearch
//                );
//            }, threadPoolExecutor);

    }

    @Override
    public Long countRead(Long projectId) {

        R<Long> r = searchFeignService.countRead(projectId);

        return r.isSuccessful() ? r.getData() : 0L;
    }


}
